package br.com.simora.http;


import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.log4j.Logger;

public class HttpTools {
	private static Logger logger = Logger.getLogger(HttpTools.class);
	private Pagina pagina;
	private final String USER_AGENT = "Mozilla/5.0";
	
    public Pagina getHTML(String urlToRead) {
    	pagina = new Pagina();
      URL url;
      HttpURLConnection conn;
      String charset = "";
      StringBuilder strB = new StringBuilder();
      try {
         url = new URL(urlToRead);
         conn = (HttpURLConnection) url.openConnection();
       
         conn.setRequestMethod("GET");
         conn.setRequestProperty("User-Agent", USER_AGENT);
         BufferedReader input = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
         String contentType = conn.getContentType();
         String[] values = contentType.split(";"); //The values.length must be equal to 2...

         if(values != null){
	         for (String value : values) {
	             value = value.trim();
	
	             if (value.toLowerCase().startsWith("charset=")) {
	                 charset = value.substring("charset=".length());
	             }
	         }
         }
         //logger.debug("CHARSET " + charset);
         String str;
         while (null != (str = input.readLine())) {
             strB.append(str); 
         }
         input.close();
      } catch (Exception e) {
    	  logger.debug(e.getMessage());
         e.printStackTrace();
      }
      pagina.setConteudo(strB.toString());
      pagina.setContentType(charset);
      return pagina;
   }
    
    public Pagina postHTML(String url, String urlParameters) {
    	logger.debug("PATH: " + urlParameters);
    	pagina = new Pagina();
    	String charset = "";
    	StringBuffer response = new StringBuffer();
    	try {
			URL obj = new URL(url);
			HttpURLConnection con = (HttpURLConnection) obj.openConnection();
	 
			//add reuqest header
			con.setRequestMethod("POST");
			con.setRequestProperty("User-Agent", USER_AGENT);
			con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
			con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
	 
			// Send post request
			con.setDoOutput(true);
			DataOutputStream wr = new DataOutputStream(con.getOutputStream());
			wr.writeBytes(urlParameters);
			wr.flush();
			wr.close();
			
			//int responseCode = con.getResponseCode();
			BufferedReader in = new BufferedReader(
			        new InputStreamReader(con.getInputStream()));
			String contentType = con.getContentType();
	        String[] values = contentType.split(";"); //The values.length must be equal to 2...
	
	        if(values != null){
		         for (String value : values) {
		             value = value.trim();
		
		             if (value.toLowerCase().startsWith("charset=")) {
		                 charset = value.substring("charset=".length());
		             }
		         }
	        }
			String inputLine;
	 
			while ((inputLine = in.readLine()) != null) {
				response.append(inputLine);
			}
			in.close();
    	} catch (Exception e) {
    		logger.debug("EXCEPTION: " + e.getMessage());
            e.printStackTrace();
         }
    	logger.debug("RESPOSTA: " + response.toString());
		pagina.setConteudo(response.toString());
	    pagina.setContentType(charset);
	    return pagina;
	}
    
    public String sendPostJson(String urlDest, String json){
        String result = "";
        try {
        	URL url = new URL(urlDest);
            HttpPost httpPost = new HttpPost(urlDest);
            StringEntity entity = new StringEntity(json);
            entity.setContentType("application/json");
            HttpURLConnection conn;
            httpPost.setEntity(entity);
            String line;
            BufferedReader rd;
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30 * 1000).setSocketTimeout(30000).build();
            HttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
            HttpResponse response = client.execute(httpPost);
             conn = (HttpURLConnection) url.openConnection();
             conn.setRequestMethod("GET");
             rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
             while ((line = rd.readLine()) != null) {
                result += line;
             }
             rd.close();
          } catch (Exception e) {
             e.printStackTrace();
             logger.debug(e.getMessage());
          }
        logger.debug("TESTE DE " + urlDest);
        logger.debug("JSON ENVIO: " + json);
        logger.debug("JSON RETORNO: " + result);
        logger.debug("TESTE DE " + urlDest);
        return result;
    }
	
}